/**
  @file     	DESIGNPATTERN_FlyweightFactory.cpp
  @brief    	Define an interface for creating an object, and the package object is created
  @author  	arvin
  @version 	1.0   2012/12/12
 */
#include "stdafx.h"

#ifndef CXX_DESIGNPATTERN_FLYWEIGHTFACTORY_H
#include "DESIGNPATTERN_FlyweightFactory.h"
#endif

#ifndef CXX_DESIGNPATTERN_FLYWEIGHT_H
#include "DESIGNPATTERN_Flyweight.h"
#endif

#ifndef CXX_DESIGNPATTERN_CONCRETEFLYWEIGHT_H
#include "DESIGNPATTERN_ConcreteFlyweight.h"
#endif

FlyweightFactory* FlyweightFactory::m_pInstance = NULL;


/**
* Construction
*
* @param VOID
* @return 
*/
FlyweightFactory::FlyweightFactory()
{
	DEBUG_PRINTF("");
}

/**
* Destruction
*
* @param VOID
* @return 
*/
FlyweightFactory::~FlyweightFactory()
{
	DEBUG_PRINTF("");
	list<Flyweight*>::iterator iter;
	for (iter = m_listFlyweight.begin(); iter != m_listFlyweight.end(); iter++) {
		if (NULL != *iter) {
			delete *iter;
			*iter = NULL;
		}
	}
}

/**
* Instance
*
* @param VOID
* @return FlyweightFactory*
* @note FlyweightFactory
*/
FlyweightFactory* 
FlyweightFactory::Instance()
{
	DEBUG_PRINTF("");
	if (NULL == m_pInstance) {
		m_pInstance = new FlyweightFactory;
	}
	return m_pInstance;
}


/**
* Destroy
*
* @param VOID
* @return VOID
* @note singleton
*/
VOID 
FlyweightFactory::Destroy()
{
	DEBUG_PRINTF("");
	if (NULL != m_pInstance) {
		delete m_pInstance;
		m_pInstance = NULL;
	}
}

/**
* Create Flyweight
*
* @param const string& key
* @return Flyweight* 
*/
Flyweight* 
FlyweightFactory::CreateFlyweight(const string& key)
{
	DEBUG_PRINTF("");
	Flyweight* pFlyweight = NULL;
	list<Flyweight*>::iterator iter;
	for (iter = m_listFlyweight.begin(); iter != m_listFlyweight.end(); iter++) {
		if (key == (*iter)->GetIntrinsicState()) {
			cout << "already created by users...." << endl;
			pFlyweight = *iter;
			break;
		}
	}
	
	if (NULL == pFlyweight) {
		pFlyweight = new ConcreteFlyweight(key);
		m_listFlyweight.push_back(pFlyweight);
	}
	return pFlyweight;
}

/* EOF */